package code;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author xiaovcloud
 * @description:
 * @since 2021/8/18 13:18
 */
public class FileCopyTest {
	public static void main(String[] args) {
		File srcFile = new File("/home/xiaov/java/IdeaProjects/java-daily-questions/40/2021-08-18/file/from.txt");
		String srcItem = readFile(srcFile);
		System.out.println("文件的内容为：");
		System.out.println(srcItem);
		System.out.println();
		System.out.println("正在复制文件...");
		File targetFile = new File("/home/xiaov/java/IdeaProjects/java-daily-questions/40/2021-08-18/file/to.txt");
		if (!targetFile.exists()){
			try {
				targetFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println(targetFile.getAbsoluteFile());
		copy(srcFile,targetFile);
		System.out.println("文件复制完成");
	}

	/**
	 * 读取文件内容
	 * @param file
	 */
	public static String readFile(File file)  {
		FileInputStream fileInputStream = null;
		ByteBuffer buf = ByteBuffer.allocate(1024);
		CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
		StringBuilder result =new StringBuilder();
		FileChannel channel = null;
		try {
			fileInputStream = new FileInputStream(file);
			channel = fileInputStream.getChannel();
			while(channel.read(buf)!=-1) {
				//
				buf.flip();
				result.append(decoder.decode(buf));
				buf.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				//关闭通道
				Objects.requireNonNull(channel).close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result.toString();
	}

	/**
	 * 复制文件
	 * @param src
	 * @param target
	 */
	public static void copy(File src,File target){
		try {
			FileChannel srcChannel = new FileInputStream(src).getChannel();
			FileChannel targetChannel = new FileOutputStream(target).getChannel();
			srcChannel.transferTo(0,srcChannel.size(),targetChannel);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
